package com.gusha.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;

public class BeanConvertor {

	public static Object convertBean2Bean(Object from, Object to) {
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(to.getClass());
			PropertyDescriptor[] ps = beanInfo.getPropertyDescriptors();

			for (PropertyDescriptor p : ps) {
				Method getMethod = p.getReadMethod();
				Method setMethod = p.getWriteMethod();
				if (getMethod != null && setMethod != null) {
					try {
						Object result = getMethod.invoke(from);
						setMethod.invoke(to, result);
					} catch (Exception e) {
						// 如果from没有此属性的get方法，跳过
						continue;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return to;
	}

	/**
	 * 方法说明：将bean转化为另一种bean实体
	 * 
	 * @param object
	 * @param entityClass
	 * @return
	 */
	public static <T> T convertBean(Object object, Class<T> entityClass) {
		if (null == object) {
			return null;
		}
		return JSON.parseObject(JSON.toJSONString(object), entityClass);
	}

	/**
	 * 方法说明：对象转换
	 * 
	 * @param source
	 *            原对象
	 * @param target
	 *            目标对象
	 * @param ignoreProperties
	 *            排除要copy的属性
	 * @return
	 */
	public static <T> T copy(Object source, Class<T> target, String... ignoreProperties) {
		T targetInstance = null;
		try {
			targetInstance = target.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (ArrayUtils.isEmpty(ignoreProperties)) {
			BeanUtils.copyProperties(source, targetInstance);
		} else {
			BeanUtils.copyProperties(source, targetInstance, ignoreProperties);
		}
		return targetInstance;

	}

	/**
	 * 方法说明：对象转换(List)
	 * 
	 * @param list
	 *            原对象
	 * @param target
	 *            目标对象
	 * @param ignoreProperties
	 *            排除要copy的属性
	 * @return
	 */
	public static <T, E> List<T> copyList(List<E> list, Class<T> target, String... ignoreProperties) {
		List<T> targetList = new ArrayList<>();
		if (CollectionUtils.isEmpty(list)) {
			return targetList;
		}
		for (E e : list) {
			targetList.add(copy(e, target, ignoreProperties));
		}
		return targetList;
	}
}
